import classNames from 'classnames';
import { format } from 'date-fns';
import { useRef, useState } from 'react';
import Calendar from '../Calendar';
import style from './DatePicker.module.scss';

type Props = {
  value?: Date;
  onChange?: (v: Date) => void;
  className?: string;
};

const DatePicker = ({ value = new Date(), onChange, className }: Props) => {
  const ref = useRef<HTMLDivElement>(null);
  const [open, setOpen] = useState<boolean>(false);

  const onDateClick = (v: Date) => {
    setOpen(false);
    onChange && onChange(v);
  };

  return (
    <>
      <div
        className={classNames(style.input, { [style.active]: open }, className)}
        ref={ref}
        onClick={() => setOpen(true)}
      >
        {format(value, 'yyyy/MM/dd')}
      </div>
      <Calendar
        open={open}
        onClose={() => setOpen(false)}
        anchorEl={ref.current}
        value={value}
        onChange={onDateClick}
      />
    </>
  );
};

export default DatePicker;
